package commons.client;

import java.util.ArrayList;
import java.util.List;

import provisioning.ranjan.RanjanCollector;
import provisioning.ranjan.RanjanDataCalculator;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.services.autoscaling.AmazonAutoScaling;
import com.amazonaws.services.autoscaling.AmazonAutoScalingClient;
import com.amazonaws.services.autoscaling.model.AutoScalingGroup;
import com.amazonaws.services.autoscaling.model.EnabledMetric;
import com.amazonaws.services.autoscaling.model.PutScalingPolicyRequest;
import com.amazonaws.services.autoscaling.model.PutScalingPolicyResult;

public class Scheduler {
	
	private static Scheduler scheduler;
	private AmazonAutoScaling autoScheduler;
	private RanjanDataCalculator ranjanCalculator;
	
	private Scheduler() {
		autoScheduler = new AmazonAutoScalingClient(new AWSCredentials() {
			@Override
			public String getAWSSecretKey() {
				return System.getProperty(UserModel.AWS_SECRET_KEY);
			}
			@Override
			public String getAWSAccessKeyId() {
				return System.getProperty(UserModel.AWS_ACCESS_KEY_ID);
			}
		});
		
		UserModel usr = new UserModel();
		this.ranjanCalculator = new RanjanDataCalculator(new RanjanCollector(usr));
	}
	
	public static Scheduler getScheduler() {
		if(scheduler == null) {
			new Scheduler();
		} return scheduler;
	}
	
	/**
	 * Link the auto scaling groups to enable metrics 
	 */
	public void groupsInitialization(String configName, String instanceType, UserModel client) {
		EnabledMetric metric1 = new EnabledMetric();
		metric1.setMetric("CPUUtilization");
		
		List<EnabledMetric> enableMetrics = new ArrayList<EnabledMetric>();
		enableMetrics.add(metric1);
		
		for(AutoScalingGroup group : client.getGroups()) {
			new GroupConnection(group, enableMetrics, configName, instanceType);
		}
	}
	
	public String ranjanScaling() {
		PutScalingPolicyRequest policyUp = new PutScalingPolicyRequest();
		policyUp.setScalingAdjustment(ranjanCalculator.evaluateNumberOfServersForNextInterval());
		
		PutScalingPolicyResult ranjanUP = autoScheduler.putScalingPolicy(policyUp);
		return ranjanUP.getPolicyARN();
	}
	
}
